package com.czk.server;

import com.czk.codec.ObjectDecoder;
import com.czk.codec.ObjectEncode;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.nio.charset.Charset;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/4/28 10:34
 */
public class NettyServer {
    public void bind(String host, Integer port) {
        // 线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup();
        //
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
            /*                pipeline.addLast(new ObjectDecoder(String.class));
                            pipeline.addLast(new ObjectEncode(String.class));*/
                            // 加入心跳检测处理器
                            pipeline.addLast(new IdleStateHandler(2, 2, 2));
                            // 基于换行符号
                            pipeline.addLast(new LineBasedFrameDecoder(1024));
                            // 解码转String，注意调整自己的编码格式GBK、UTF-8
                            pipeline.addLast(new StringDecoder(Charset.forName("GBK")));
                            // 解码转String，注意调整自己的编码格式GBK、UTF-8
                            pipeline.addLast(new StringEncoder(Charset.forName("GBK")));
                            // 在管道中添加我们自己的接收数据实现方法
                            pipeline.addLast(new NettyServerHandler());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(host, port).sync();
            System.out.println("服务器启动成功");
            channelFuture.channel().closeFuture().sync();
            System.out.println("阻塞中");
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        NettyServer server=new NettyServer();
        server.bind("localhost",7379);
    }
}
